'use strict';

const Service = require('egg').Service;

class ReportService extends Service {


  /**
   *获取列表
   * @param {载荷} payload
   * @return {Promise<>}
   */
  async getList(payload) {
    const { app } = this;
    const Op = app.Sequelize.Op;
    const { pageNum, pageSize, type, user_id, article_id, status, keywords, begin_pubdate, end_pubdate } = payload;
    const where = {};
    if (type) { where.type = type; }
    if (user_id) { where.user_id = user_id; }
    if (article_id) { where.article_id = article_id; }
    if (status) { where.status = status; }
    if (keywords) { where.remark = { [Op.like]: `%${keywords}%` }; }
    if (begin_pubdate && end_pubdate) {
      where.createdAt = { [Op.between]: [ begin_pubdate, end_pubdate ] };
    }// 查询这个字段-xx之间  }
    // notBetween
    try {
      const { count, rows } = await app.model.NewsReport.findAndCountAll({
        where,
        attributes: { exclude: [ 'deletedAt', 'updatedAt' ] }, // 不显示哪些字段
        order: [[ 'createdAt', 'desc' ]], // 根据创建时间倒序排序
        include: [
          {
            model: this.app.model.Article,
            as: 'article',
            attributes: [ 'title' ], // 只显示哪些字段
          },
          {
            model: this.app.model.User,
            as: 'user',
            attributes: [ 'user_name' ], // 只显示哪些字段
          },
        ],
        offset: (pageNum - 1) * pageSize,
        limit: pageSize * 1,
      });
      return {
        pageNum,
        pageSize,
        total: count,
        list: rows,
      };
    } catch (error) {
      console.error(error);
      return null;
    }
  }

  // 删除
  async del(payload) {
    const { app } = this;
    console.log(payload);
    return await app.model.NewsReport.destroy({ where: { id: payload.ids }, force: true });
  }

  // 修改
  async updated(id, payload) {
    const { app } = this;
    return await app.model.NewsReport.update(payload, { where: { id } });
  }

  // 根据id获取信息
  async getInfo(id) {
    return await this.app.model.NewsReport.findByPk(id);
  }

}

module.exports = ReportService;
